<?php
	require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/database.php';
	require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/doctype.php';
	
	//Get photo
	$id = 0;
	if (isset($_GET['id'])) $id = $_GET['id'];

	if (isset($_POST['edit'])) {
		//Update picture
		mysql_query("UPDATE photos SET " .
				"title='" . $_POST['title'] . "', " .
				"description='" . $_POST['description'] . "', " .
				"category_id='" . $_POST['category'] . "', " .
				"date_taken='" . $_POST['date'] . "', " .
				"view_privilege='" . $_POST['view-privilege'] . "', " .
				"comment_privilege='" . $_POST['comment-privilege'] . "' " .
				"WHERE id='$id'") or die(mysql_error());

		//Delete old keywords
		mysql_query("DELETE FROM keywords WHERE photo_id='$id'") or die(mysql_error());

		//While there's still a keyword
		$text	= $_POST['keywords'];
		$token	= strtok($text, ",");
		while ($token) {
			//Trim whitespace then insert it
			$keyword = trim($token);
			mysql_query("INSERT INTO keywords (photo_id, keyword) VALUES ('" . $id . "','" . $keyword . "')") or die(mysql_error());

			//Next
			$token = strtok(",");
		}

		//Get owner
		$result = mysql_query("SELECT user_id FROM tags WHERE photo_id='$id' AND is_owner='1'") or die(mysql_error());
		$owner	= mysql_fetch_array($result);

		//Delete old tags
		mysql_query("DELETE FROM tags WHERE photo_id='$id' AND is_owner='0' ");
		mysql_query("UPDATE tags SET is_tagged='0' WHERE photo_id='$id' AND user_id='" . $owner['user_id'] . "'");

		//While there's still a keyword
		$text	= $_POST['tags'];
		$token	= strtok($text, ",");
		while ($token) {
			//Trim whitespace
			$tagged = trim($token);

			//Find ID
			$result = mysql_query("SELECT id FROM users WHERE username='" . $tagged . "'");
			if (mysql_num_rows($result) > 0) {
				//If valid, add to tags
				$row = mysql_fetch_array($result);
				if ($row['id'] == $owner['user_id']) mysql_query ("UPDATE tags SET is_tagged='1' WHERE photo_id='$id' AND user_id='" . $row['id'] . "'") or die(mysql_error());
				else							mysql_query("INSERT INTO tags (photo_id, user_id) VALUES ('$id','" . $row['id'] . "')") or die(mysql_error());
			}

			//Next
			$token = strtok(",");
		}
	}
	
	$photo	= NULL;
	$owner	= NULL;
	$result = mysql_query("SELECT * FROM photos WHERE id=$id") or die(mysql_error());
	if (mysql_num_rows($result) >= 1) {
		$photo = mysql_fetch_array($result);

		//Find owner
		$result = mysql_query("SELECT user_id FROM tags WHERE photo_id='" . $photo['id'] . "' AND is_owner='1'");
		$row	= mysql_fetch_array($result);
		$result	= mysql_query("SELECT * FROM users WHERE id='" . $row['user_id'] . "'");
		$owner	= mysql_fetch_array($result);
	}

	//Get tags
	$tag_string = "";
	$result		= mysql_query("SELECT user_id FROM tags WHERE photo_id='" . $photo['id'] . "' AND is_tagged='1'");
	$row		= mysql_fetch_array($result);
	while ($row) {
		//Get name
		$name_result	= mysql_query("SELECT username FROM users WHERE id='" . $row['user_id'] . "'");
		$name_row		= mysql_fetch_array($name_result);

		//Append
		$tag_string .= '<a href="/deviantpic/user/profile/index.php?id=' . $row['user_id'] . '">';
		$tag_string .= $name_row['username'];
		$tag_string .= "</a>";

		//Next
		$row = mysql_fetch_array($result);
		if ($row) $tag_string .= ", ";
	}

	//Get keywords
	$keyword_string = "";
	$result			= mysql_query("SELECT keyword FROM keywords WHERE photo_id='" . $photo['id'] . "'");
	$row			= mysql_fetch_array($result);
	while ($row) {
		$keyword_string .= $row['keyword'];
		$row = mysql_fetch_array($result);
		if ($row) $keyword_string .= ", ";
	}
	
	//check follower and ownership
	$following = FALSE;
	$is_owner = FALSE;
	
	if (isset($_SESSION['user'])) {
		if ($owner['id'] != $_SESSION['user']) {
			//Check database
			$photo_result = mysql_query("SELECT * FROM followers WHERE user_id=" . $owner['id'] . " AND follower_id=" . $_SESSION['user']) or die(mysql_error());
			if (mysql_num_rows($photo_result) > 0) $following = TRUE;
		} else $is_owner = TRUE;
	}
	
	//get permission variables
	$can_comment = FALSE;
	if ($photo['comment_privilege']==1) $can_comment = TRUE;
	
	$can_view = FALSE;
	$view = $photo['view_privilege'];
	if (($view==1)||
		($view==2&& isset($_SESSION['user']))||
		(($view==3&&$following)||$is_owner)||
		($view==4&&$is_owner)) {
		$can_view = TRUE;
	}

	$has_rate = false;
	if (isset($_SESSION['user'])) {
		$result = mysql_query("SELECT * FROM photo_ratings WHERE user_id='" . $_SESSION['user'] . "' AND photo_id='" . $photo['id'] . "'");
		if (mysql_num_rows($result) >= 1) $has_rate = true;
	} else $has_rate = true;
	
	//check new comment
	if (isset($_POST['comment'])) {
		//Add new post to the database
		mysql_query("INSERT INTO photo_comments (photo_id, user_id, content)
			VALUES('" . $photo['id'] . "','" . $_SESSION['user'] . "','" . $_POST['comment'] . "')") or die(mysql_error());
	}
	
	//check new rating
	if (isset($_POST['rating'])) {
		mysql_query("INSERT INTO photo_ratings (user_id, photo_id, rating)
			VALUES('" . $_SESSION['user'] . "','" . $photo['id'] . "','" . $_POST['rating'] . "')") or die(mysql_error());
	}
	
	//load comments
	$start = 0;
	if (isset($_GET['start'])) $start = $_GET['start'];

	$comments = array();
	$comments_result = mysql_query("SELECT * FROM photo_comments WHERE photo_id=" . $photo['id'] . " ORDER BY time DESC") or die (mysql_error());
	$comments_row	= mysql_fetch_array($comments_result);
	
	$index	= 0;
	$amount	= $comments_in_picture;
	
	while ($comments_row && count($comments) < $amount) {
		//Starting from start
		if  ($index >= $start) {
			//Insert to photo
			$comments[] = $comments_row;
			$comments_row = mysql_fetch_array($comments_result);
		}
	}
	
	//calculate rating
	$rating = 0;
	$rating_result = mysql_query("SELECT * FROM photo_ratings WHERE photo_id=" . $photo['id']) or die (mysql_error());
	$rating_row = mysql_fetch_array($rating_result);
	
	$index = 0;
	$index_max = mysql_num_rows($rating_result);
	
	while($index<$index_max) {
		$rating += $rating_row['rating'];
		
		$rating_row = mysql_fetch_array($rating_result);
		$index++;
	}
	
	if ($index_max!=0) $rating /= $index_max;
?>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <script type="text/javascript" src="/deviantpic/script/comments.js"></script>
        <title>deviantPIC - <?php echo $photo['title']?> </title>
    </head>
    <body>
		<!-- Header -->
		<?php require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/header.php'; ?>

		<!-- Content -->
		<div id="body">
			<div id="photo-header">
				<div id="photo-header-title"><?php echo $photo['title'] ?></div>
				<?php
					if ($is_owner) {
				?>
				<div id="photo-header-edit"><a id="photo-edit" href=<?php echo '"' . "/deviantpic/picture/edit.php?id=" . $photo['id'] . '"'; ?>>edit</a></div>
				<?php
					}
				?>
				<div id="photo-header-owner">
					by
					<span class="photo-owner">
						<a href=<?php echo '"/deviantpic/user/profile/index.php?id=' . $owner['id']  . '"' ?>><?php echo $owner['username'] ?></a>
					</span>
				</div>
			</div>

			<!-- Photo Canvas -->
			<div id="photo-canvas">
				<?php 
					if(!$can_view) echo '<div id="photo-cannot-view"> You do not have permission required to view this photo. </div>';
					else {
						//Show photo and information
						$category = null;
						$category_result = mysql_query("SELECT * FROM categories WHERE id=". $photo['category_id']) or die(mysql_error());
						if (mysql_num_rows($category_result) >= 1) $category = mysql_fetch_array($category_result);
						
						echo '
							<div id="photo-frame">
							<img src="' . $photo['photo'] . '" />
							</div>
							
							<div id="photo-information>
								<div id="photo-description"> Description : ' . $photo['description'] . ' </div>
								<div id="photo-category"> Category : ' . $category['name'] . ' </div>
								<div id="photo-keywords"> Keywords : ' . $keyword_string . ' </div>
								<div id="photo-tags"> Tags : ' . $tag_string . ' </div>
								<div id="photo-date"> Date Taken : ' . $photo['date_taken'] . ' </div>
								<div id="photo-date-uploaded"> Date Uploaded : ' . $photo['time_uploaded'] . ' </div>
							</div>
						';
					} 
				?>
			</div>
			
			<!-- Photo Ratings -->
			<div id="photo-ratings">
				<div id="photo-total-rating"> Total Rating : <?php echo $rating ?> </div>
				<?php 
					if ($can_view && !$is_owner && !$has_rate) {
						echo '
							<div class="photo-rating-form">
								<form action="view.php?id=' . $photo['id'] . '" method="post">
									<!-- Header -->
									<div id="photo-rating-header"> Rate this photo! </div>
									
									<!-- Content input -->
									<select id="photo-rating-value" name="rating">
										<option class="photo-rating-value-option" value="-1">-1</option>
										<option class="photo-rating-value-option" value="0">0</option>
										<option class="photo-rating-value-option" value="+1">+1</option>
									</select>
					
									<!-- Button -->
									<input type="submit" value="Rate" />
								</form>
							</div>
						';				
					}
				?>
			</div>
			
			<!-- Photo Comments -->			
			<div id="photo-comments">
				<?php
					//For each comment
					foreach ($comments as $comment) {
						//Get poster name
						$result = mysql_query("SELECT * FROM users WHERE id=" . $comment['user_id']) or die(mysql_error());
						$poster = mysql_fetch_array($result);
				?>
					<!-- Photo Comment -->
					<div class="photo-comment">
						<div class="photo-comment-header"> 
							<div class=photo-comment-poster> <?php echo $poster['username'] ?> </div>
							<div class=photo-comment-time> <?php echo $comment['time'] ?></div>
						</div>
						<div class="photo-comment-content"> 
							<?php echo $comment['content'] ?>
						</div>
					</div>
				<?php
					}
					echo "<a href=\"javascript:getPictureComments(".$photo['id'].");\"><b>[View All Comments]</b></a>&nbsp;&nbsp;&nbsp;\n";
				?>
			</div>
			
			<!-- Photo Comment Form -->
			<?php 
				if (!$can_comment||!$can_view) echo '<div id="photo-comment-form-cannot"> Comment is disabled for this photo. </div>';
				else {
					echo "
					<div class='photo-comment-form'>
						<form action='view.php?id=" . $photo['id'] . "' method='post'>
						<!-- Header -->
						<div id='photo-comment-form-header'> Write your comment here! </div>
						
						<!-- Content input -->
						<textarea cols='32' rows='2' class='input-photo-comment' name='comment'>Write comment</textarea>
						<br />
		
						<!-- Button -->
						<input type='submit' value='Comment' />
						</form>
					</div>
					";
				}
			?>			
		</div>

		<!-- Footer -->
		<?php require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/footer.php'; ?>
    </body>
</html>